﻿import VTitle from '@/components/common/MainTitle.vue'
import AddExpress from './AddExpress.vue'
import AddParameter from './addParameter.vue'
export default {
  components: { VTitle, AddExpress, AddParameter },
  data () {
    return {
      titleName: '新增数据集信息',
      loading: false,
      searchTableVal: '',
      currentTabs: 'metaTable',
      metaTableList: [], // 元数据表
      metaTableList_all: [], // 所有的元数据表
      sourceList: [], // 数据源的列表
      currentSource: '', // 当前选中的数据源
      sourceTableList: [], // 数据源表
      sourceTableList_all: [], // 所有的数据源表
      sourceViewList: [], // 数据源视图
      sourceViewList_all: [], // 所有的数据源视图
      dialogInfo: {
        operationType: '',
        rowInfo: null
      },
      checkedInfo: {
        sourceId: '', // 数据源的id
        tableId: '', // 元数据表的id或数据源表的name
        columns: [] // 指定数据表的字段信息
      },
      // 新增数据集字段部分
      ruleForm: {
        title: '', // 数据集名称
        id: '', // 指定的表名称
        as: '', // 别名
        join: null, // join表达式
        dimensionArray: [], // 维度表达式
        measurementArray: [], // 量度表达式
        where: null, // 条件表达式
        orderby: null, // 排序表达式
        parameters: [] //参数设定
      },
      // 表单规则部分
      rules: {
        title: [
          {required: true, message: '数据集不能为空', trigger: 'blur'}
        ]
      },
      labelWidth: '130px',
      addExpressDialog: {
        dialogFormVisible: false,
        keyStr: '',
        keyName: '',
        keyExpress: '',
        type: '',
        index: 0,
        columnsList: null
      },
      addParameterDialog: {
        dialogFormVisible: false,
        index: 0,
        source: '',
        param_name: '',
        table: '',
        as: '',
        join: '',
        action: '',
        column: '',
        filter: '',
        group: ''
      }
    }
  },
  created () {
    let dialogInfoObj = this.$route.query.info ? JSON.parse(this.$route.query.info) : null
    if (dialogInfoObj) {
      this.dialogInfo.operationType = dialogInfoObj.operationType
      this.titleName = dialogInfoObj.operationType === 'add' ? '新增数据集信息' : (dialogInfoObj.operationType === 'edit' ? '编辑数据集信息' : '数据集详情')
      this.dialogInfo.rowInfo = dialogInfoObj.rowInfo
      this.ruleForm.parameters = dialogInfoObj.operationType === 'add' ? [] : this.dialogInfo.rowInfo.parameters
      if (this.dialogInfo.operationType !== 'add' && this.dialogInfo.rowInfo && this.dialogInfo.rowInfo.bi_express) {
        let biExpressObj = JSON.parse(this.dialogInfo.rowInfo.bi_express)
        this.checkedInfo.sourceId = this.dialogInfo.rowInfo.source_uid
        this.checkedInfo.tableId = biExpressObj.id
        this.ruleForm.id = biExpressObj.id
        this.ruleForm.as = biExpressObj.as
        this.ruleForm.join = biExpressObj.join
        this.ruleForm.orderby = biExpressObj.orderby
        this.ruleForm.where = biExpressObj.where
        this.ruleForm.title = this.dialogInfo.rowInfo.title
        this.ruleForm.dimensionArray = []
        this.ruleForm.measurementArray = []
        if (biExpressObj.dimension) {
          for (let key in biExpressObj.dimension) {
            let obj = {
              keyStr: key,
              keyName: (biExpressObj.dimension_title && biExpressObj.dimension_title[key]) ? biExpressObj.dimension_title[key] : key,
              keyExpress: biExpressObj.dimension[key]
            }
            this.$set(this.ruleForm.dimensionArray, this.ruleForm.dimensionArray.length, obj)
          }
        }
        if (biExpressObj.measurement) {
          for (let key in biExpressObj.measurement) {
            let obj = {
              keyStr: key,
              keyName: (biExpressObj.measurement_title && biExpressObj.measurement_title[key]) ? biExpressObj.measurement_title[key] : key,
              keyExpress: biExpressObj.measurement[key]
            }
            this.$set(this.ruleForm.measurementArray, this.ruleForm.measurementArray.length, obj)
          }
        }
      }
    }
    this.getAllData()
  },
  methods: {
    // 获取所有的数据源
    getAllData () {
      this.loading = true
      this.getTableData()
    },
    // 获取所有的元数据表
    getTableData () {
      this.metaTableList = []
      this.metaTableList_all = []
      this.currentTabs = 'metaTable'
      this.$get('/metadata').then(data => {
        if (data.status === 200) {
          this.metaTableList_all = data.data.result
          if (!this.checkedInfo.sourceId && this.checkedInfo.tableId) { // 没有数据源id,但是有表的id,则选中的是元数据表中
            for (let i = 0; i < this.metaTableList_all.length; i++) {
              if (this.checkedInfo.tableId === this.metaTableList_all[i].metaname) {
                this.checkedInfo.columns = this.metaTableList_all[i].columns
                break
              }
            }
          }
          this.getActiceSourceList()
        } else {
          this.$message({
            type: 'error',
            message: data.statusText
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取启用的数据源列表
    getActiceSourceList () {
      this.currentSource = ''
      this.$get('/data_source/activelist').then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.sourceList = dataResult.data
          if (this.sourceList.length) {
            if (this.checkedInfo.sourceId) {
              this.currentSource = this.checkedInfo.sourceId
            } else {
              this.currentSource = this.sourceList[0].SourceUID
            }
            this.getCurrentSourceTable()
          } else {
            this.getShowList()
            this.loading = false
          }
        } else {
          this.$message({
            type: 'error',
            message: dataResult.msg
          })
          this.loading = false
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取指定的数据源的表格
    getCurrentSourceTable () {
      this.sourceTableList = [] // 数据源表
      this.sourceTableList_all = [] // 所有的数据源表
      this.sourceViewList = [] // 数据源视图
      this.sourceViewList_all = [] // 所有的数据源视图
      if (!this.currentSource) {
        return
      }
      this.loading = true
      this.$get('/data_source/' + this.currentSource + '/allobjects').then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.sourceTableList_all = dataResult.data.table_list // 数据源表
          this.sourceViewList_all = dataResult.data.view_list // 数据源视图
          if (this.checkedInfo.sourceId && this.checkedInfo.tableId) {
            let hadChecked = false
            for (let i = 0; i < this.sourceTableList_all.length; i++) {
              if (this.checkedInfo.tableId === this.sourceTableList_all[i].table_name) {
                hadChecked = true
                this.currentTabs = 'sourceTable'
                this.loading = true
                this.getColumnsOfSourceTable(this.currentSource, this.checkedInfo.tableId)
                break
              }
            }
            if (!hadChecked) {
              for (let i = 0; i < this.sourceViewList_all.length; i++) {
                if (this.checkedInfo.tableId === this.sourceViewList_all[i].view_name) {
                  this.currentTabs = 'sourceView'
                  this.loading = true
                  this.getColumnsOfSourceView(this.currentSource, this.checkedInfo.tableId)
                  break
                }
              }
            }
          }
          this.getShowList()
        } else {
          this.$message({
            type: 'error',
            message: dataResult.msg
          })
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    // 获取展示的数据
    getShowList () {
      if (this.$trim(this.searchTableVal)) {
        this.metaTableList_all.forEach(item => {
          if (item.metaname.indexOf(this.searchTableVal) !== -1 || (item.metadesc && item.metadesc.indexOf(this.searchTableVal) !== -1)) {
            this.$set(this.metaTableList, this.metaTableList.length, item)
          }
        })
        this.sourceTableList_all.forEach(item => {
          if (item.table_name && item.table_name.indexOf(this.searchTableVal) !== -1) {
            this.$set(this.sourceTableList, this.sourceTableList.length, item)
          }
        })
        this.sourceViewList_all.forEach(item => {
          if (item.view_name && item.view_name.indexOf(this.searchTableVal) !== -1) {
            this.$set(this.sourceViewList, this.sourceViewList.length, item)
          }
        })
      } else {
        this.metaTableList = this.metaTableList_all.length ? JSON.parse(JSON.stringify(this.metaTableList_all)) : []
        this.sourceTableList = this.sourceTableList_all.length ? JSON.parse(JSON.stringify(this.sourceTableList_all)) : []
        this.sourceViewList = this.sourceViewList_all.length ? JSON.parse(JSON.stringify(this.sourceViewList_all)) : []
      }
    },
    // 切换选中的表时
    changeCheckedTable (item) {
      if (this.currentTabs === 'metaTable') { // 元数据表
        if (this.checkedInfo.tableId === item.metaname) {
          return
        } else {
          if (this.checkedInfo.tableId) {
            this.$confirm('确定切换当前表?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              cancelButtonClass: 'el-button--info'
            }).then(() => {
              this.loading = true
              this.setCheckedTableInfo(null, item.metaname, item.columns)
            }).catch(() => {})
          } else {
            this.loading = true
            this.setCheckedTableInfo(null, item.metaname, item.columns)
          }
        }
      } else if (this.currentTabs === 'sourceTable') { // 数据源表
        if (this.checkedInfo.tableId === item.table_name) {
          return
        } else {
          if (this.checkedInfo.tableId) {
            this.$confirm('确定切换当前表?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              cancelButtonClass: 'el-button--info'
            }).then(() => {
              this.loading = true
              this.getColumnsOfSourceTable(this.currentSource, item.table_name)
            }).catch(() => {})
          } else {
            this.loading = true
            this.getColumnsOfSourceTable(this.currentSource, item.table_name)
          }
        }
      } else if (this.currentTabs === 'sourceView') { // 数据源视图
        if (this.checkedInfo.tableId === item.view_name) {
          return
        } else {
          if (this.checkedInfo.tableId) {
            this.$confirm('确定切换当前表?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              cancelButtonClass: 'el-button--info'
            }).then(() => {
              this.loading = true
              this.getColumnsOfSourceView(this.currentSource, item.view_name)
            }).catch(() => {})
          } else {
            this.loading = true
            this.getColumnsOfSourceView(this.currentSource, item.view_name)
          }
        }
      }
    },
    // 获取数据源表的字段信息
    getColumnsOfSourceTable (sourceId, tableId) {
      this.$get('/data_source/' + sourceId + '/table/' + tableId + '/schema').then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.setCheckedTableInfo(sourceId, tableId, dataResult.data)
        } else {
          this.$message({
            type: 'error',
            message: dataResult.msg
          })
          this.loading = false
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取数据源视图的字段信息
    getColumnsOfSourceView (sourceId, tableId) {
      this.$get('/data_source/' + sourceId + '/view/' + tableId + '/schema').then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.setCheckedTableInfo(sourceId, tableId, dataResult.data)
        } else {
          this.$message({
            type: 'error',
            message: dataResult.msg
          })
          this.loading = false
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 设置选中的表
    setCheckedTableInfo (sourceId, tableId, columns) {
      this.checkedInfo.sourceId = sourceId
      this.checkedInfo.tableId = tableId
      this.ruleForm.id = tableId
      this.ruleForm.as = tableId
      this.checkedInfo.columns = columns
      this.loading = false
    },
    // 新增的方法
    addMethod (bi_express) {
      this.$post('/icpdataset', {
        title: this.ruleForm.title,
        source_uid: this.checkedInfo.sourceId,
        bi_express: bi_express,
        parameters: btoa(encodeURIComponent(JSON.stringify(this.ruleForm.parameters)))
      }).then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.$message({
            type: 'success',
            message: '新增成功'
          })
          this.goBack()
        } else {
          this.$message({
            type: 'error',
            message: dataResult.msg
          })
        }
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.$message({
          type: 'error',
          message: error
        })
      })
    },
    // 编辑的方法
    editMethod (bi_express) {
      this.$patch('/icpdataset/' + this.dialogInfo.rowInfo.uid, {
        title: this.ruleForm.title,
        source_uid: this.checkedInfo.sourceId,
        bi_express: bi_express,
        parameters: btoa(encodeURIComponent(JSON.stringify(this.ruleForm.parameters)))
      }).then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
          this.goBack()
        } else {
          this.$message({
            type: 'error',
            message: dataResult.msg
          })
        }
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.$message({
          type: 'error',
          message: error
        })
      })
    },
    // 测试BI表达式是否有效
    testExpressMethod () {
      if (!this.ruleForm.dimensionArray.length) {
        this.$message({
          type: 'warning',
          message: '维度表达式为空'
        })
        return
      }
      if (!this.ruleForm.measurementArray.length) {
        this.$message({
          type: 'warning',
          message: '量度表达式为空'
        })
        return
      }
      let dimension = {}
      let dimension_title = {}
      let measurement = {}
      let measurement_title = {}
      this.ruleForm.dimensionArray.forEach(item => {
        dimension[item.keyStr] = item.keyExpress
        dimension_title[item.keyStr] = item.keyName
      })
      this.ruleForm.measurementArray.forEach(item => {
        measurement[item.keyStr] = item.keyExpress
        measurement_title[item.keyStr] = item.keyName
      })
      this.loading = true
      let bi_express = {
        id: this.ruleForm.id,
        as: this.ruleForm.as,
        join: this.ruleForm.join,
        dimension: dimension,
        dimension_title: dimension_title,
        measurement: measurement,
        measurement_title: measurement_title,
        where: this.ruleForm.where,
        orderby: this.ruleForm.orderby
      }
      this.$post('/data_set/test_express', {
        source_uid: this.checkedInfo.sourceId,
        bi_express: btoa(encodeURIComponent(JSON.stringify(bi_express))),
        parameters: btoa(encodeURIComponent(JSON.stringify(this.ruleForm.parameters)))

      }).then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          if (this.dialogInfo.operationType === 'edit') {
            this.editMethod(btoa(encodeURIComponent(JSON.stringify(bi_express))))
          } else if (this.dialogInfo.operationType === 'add') {
            this.addMethod(btoa(encodeURIComponent(JSON.stringify(bi_express))))
          }
        } else {
          this.$message({
            type: 'error',
            message: dataResult.msg
          })
          this.loading = false
        }
      }).catch(error => {
        this.loading = false
        this.$message({
          type: 'error',
          message: error
        })
      })
    },
    submitForm (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.testExpressMethod()
        } else {
          return false
        }
      })
    },
    // 新增表达式成功时
    addExpressSuccess (fromAdd) {
      let obj = {
        keyStr: fromAdd.keyStr,
        keyName: fromAdd.keyName,
        keyExpress: fromAdd.keyExpress
      }
      this.$set(this.ruleForm[fromAdd.type], fromAdd.index, obj)
      this.addExpressDialog.dialogFormVisible = false
    },
    addParameterSuccess (item) {
      let obj = {
        source: item.source,
        param_name: item.param_name,
        table: item.table,
        as: item.as,
        join: item.join,
        action: item.action,
        column: item.column,
        filter: item.filter,
        group: item.group
      }
      this.$set(this.ruleForm.parameters, item.index, obj)
      this.addParameterDialog.dialogFormVisible = false
    },
    openAddExpressDialog (row, index, type) {
      if (!this.checkedInfo.tableId) {
        this.$message({
          type: 'warning',
          message: '请先选择数据表'
        })
        return
      }
      this.addExpressDialog.dialogFormVisible = true
      this.addExpressDialog.keyStr = row ? row.keyStr : ''
      this.addExpressDialog.keyName = row ? row.keyName : ''
      this.addExpressDialog.keyExpress = row ? row.keyExpress : ''
      this.addExpressDialog.type = type
      this.addExpressDialog.index = index
      this.addExpressDialog.columnsList = this.checkedInfo.columns
    },
    openAddParameterDialog (row, index) {
      this.addParameterDialog = {
        dialogFormVisible: true,
        index: index,
        source: row ? row.source : '',
        param_name: row ? row.param_name : '',
        table: row ? row.table : '',
        as: row ? row.as : '',
        join: row ? row.join : '',
        action: row ? row.action : '',
        column: row ? row.column : '',
        filter: row ? row.filter : '',
        group: row ? row.group : ''
      }
    },
    // 移除表达式的某一项时
    removeExpress (index, type) {
      this.ruleForm[type].splice(index, 1)
    },
    removeParameter (index) {
      this.ruleForm.parameters.splice(index, 1)
    },
    goBack () {
      this.$router.push('/dashboard/dataSet')
    }
  },
  watch: {
    searchTableVal: {
      handler: function (val) {
        this.metaTableList = []
        this.sourceTableList = []
        this.sourceViewList = []
        this.getShowList()
      },
      deep: true
    }
  }
}
